# coding=utf-8
import datetime
import random
import time

import pymysql as pymysql

servers = [
    '101.37.31.182:80',
    '47.98.158.184:80',
    '47.111.82.75:80'
]


class MockData:
    def __init__(self):
        self.conn = pymysql.connect(
            host='101.37.31.182',
            port=3306,
            user='root',
            password='root',
            db='fota_db',
            charset='utf8'
        )
        self.cursor = self.conn.cursor()

    def pkg_insert(self, product_num, pkg_num):
        sql_template = 'INSERT INTO pkg_version (id, product, version, uri, create_time, ' \
                       'update_time, release_time, size, size_text, description) ' \
                       'VALUES %s'
        format_str = '({id}, "{product}", "{version}", "{uri}", {create_time}, ' \
                     '{update_time}, {release_time}, {size}, "{size_text}", "{description}")'
        items, serial_id = [], 0
        for i in range(product_num):
            random_before_day = random.randint(0, 10)
            server = servers[random.randint(0, 2)]
            product = 'mock_p_%d' % i
            for j in range(pkg_num):
                serial_id += 1
                version = 'mock_p_%d_v_%d' % (i, j)
                create_time = self.get_zero_day(random_before_day + pkg_num - j)
                tmp = {
                    'id': serial_id,
                    'product': product,
                    'version': version,
                    'uri': 'http://{server}/fota-version/download/{product}/adb-1.0.31-windows.zip'.format(
                        **{'server': server, 'product': product}
                    ),
                    'create_time': create_time,
                    'update_time': 0,
                    'release_time': create_time,
                    'size': 484565,
                    'size_text': '0.46MB',
                    'description': 'adb-1.0.31-windows.zip',
                }
                items.append(tmp)
                if len(items) >= 100:
                    self.batch_insert(items, sql_template, format_str)
                    items = []
        self.batch_insert(items, sql_template, format_str)

    def plan_insert(self, product_num, pkg_num):
        sql_template = 'INSERT INTO update_plan (id, name, product, cond, src_v, ' \
                       'dst_v, create_time, update_time, description, status) VALUES %s'
        val_template = '({id}, "{name}", "{product}", "{cond}", "{src_v}", ' \
                       '"{dst_v}", {create_time}, {update_time}, "{description}", "{status}")'
        items, serial_id = [], 0
        for i in range(product_num):
            product = 'mock_p_%d' % i
            random_before_day = random.randint(0, 10)
            for j in range(pkg_num):
                serial_id += 1
                plan_name = 'mock_plan_%d' % serial_id
                src_v = ','.join(['mock_p_%d_v_%d' % (i, t-1) for t in range(j + 1)])
                dst_v = 'mock_p_%d_v_%d' % (i, pkg_num - 1)
                create_time = self.get_zero_day(random_before_day + pkg_num - j)
                tmp = {
                    'id': serial_id,
                    'name': plan_name,
                    'product': product,
                    'cond': '{}',
                    'src_v': src_v,
                    'dst_v': dst_v,
                    'create_time': create_time,
                    'update_time': 0,
                    'description': plan_name,
                    'status': 1
                }
                items.append(tmp)
                if len(items) >= 100:
                    self.batch_insert(items, sql_template, val_template)
                    items = []
        self.batch_insert(items, sql_template, val_template)

    def batch_insert(self, items, sql_template, val_template):
        if len(items) <= 0:
            return
        sql = sql_template % ','.join([val_template.format(**item) for item in items])
        print('one batch:%s' % sql)
        self.cursor.execute(sql)
        self.conn.commit()

    def log_insert(self, log_num):
        sql_template = 'INSERT INTO fota_log (id, product, imei, req_server, operator, ' \
                       'auto_download, from_v, to_v, create_time, update_time, resp_server, count) VALUES %s'
        val_template = '({id}, "{product}", "{imei}", "{req_server}", {operator}, ' \
                       '{auto_download}, "{from_v}", "{to_v}", {create_time}, {update_time}, "{resp_server}", {count})'
        items = []
        for i in range(log_num):
            serial_id = i + 1
            product_id = random.randint(0, 100)
            src_v_id = random.randint(0, 10)
            c_before_day = random.randint(0, 20)
            u_before_day = random.randint(0, c_before_day)
            tmp = {
                'id': i + 1,
                'product': 'mock_p_%d' % product_id,
                'imei': random.randint(1000000000, 9999999999),
                'req_server': servers[random.randint(0, 2)].split(':')[0],
                'operator': random.randint(1, 2),
                'auto_download': random.randint(0, 1),
                'from_v': 'mock_p_%d_v_%d' % (product_id, src_v_id),
                'to_v': 'mock_p_%d_v_%d' % (product_id, random.randint(src_v_id, 10)),
                'create_time': self.get_zero_day(c_before_day),
                'update_time': self.get_zero_day(u_before_day),
                'resp_server': servers[random.randint(0, 2)].split(':')[0],
                'count': random.randint(1, 1000000000)
            }
            items.append(tmp)
            if len(items) >= 100:
                self.batch_insert(items, sql_template, val_template)
                items = []
        self.batch_insert(items, sql_template, val_template)

    @staticmethod
    def get_zero_day(before_day):
        now = datetime.datetime.now()
        day = now - datetime.timedelta(days=before_day, hours=now.hour, minutes=now.minute, seconds=now.second,
                                       microseconds=now.microsecond)
        return int(time.mktime(day.timetuple()) * 1000)


mock_data = MockData()
if __name__ == '__main__':
    mock_data.pkg_insert(100, 10)
    mock_data.plan_insert(100, 10)
    mock_data.log_insert(10000)
